// Locate an item in array using binary search
// By DreamVB 18:20 07/10/2016

#include <iostream>

using namespace std;
using std::cout;
using std::endl;

void ShowArrayContents(int *data, int size){
	int i = 0;
	while (i < size){
		if (i < size - 1){
			cout << data[i] << ", ";
		}
		i++;
	}
	cout << data[i - 1] << endl;
}

int BinarySearch(int Items[], int lo,int hi, int findItem){
	int h = hi;
	int l = lo;
	int mid = 0;
	int idx = -1;

	while (l <= h){
		mid = (l + h) / 2;

		if (findItem == Items[mid]){
			idx = mid;
			break;
		}

		if (findItem < Items[mid]){
			h = mid - 1;
		}
		else{
			l = mid + 1;
		}
	}
	return idx;
}

int main(int argc, char *argv[]){
	int items[6] = { 10, 20, 30, 40, 50, 60 };
	int size = sizeof(items) / sizeof(*items);
	int id = 0;
	int FindValue = 30;

	//Locate the item in the array
	id = BinarySearch(items, 0, size, FindValue);

	//Show source array
	cout << "Array to look at : ";
	ShowArrayContents(items,size);

	//Check if item was found.
	if (id != -1){
		cout << FindValue << " was found in the array at index: " << id << endl;
	}
	else{
		cout << FindValue << " was not found in the array" << endl;
	}

	system("pause");
	return 0;
}